package main

import (
	"fmt"
	"zinx/ziface"
	"zinx/znet"
)

type PingRouter struct {
	znet.BaseRouter
}

// Handle 处理业务的主方法
func (pr *PingRouter) Handle(request ziface.IRequest) {
	fmt.Println("recv client msg: id = ", request.GetMsgId(), " len = ", len(request.GetData()), " msg = ", string(request.GetData()))
	// 先读取客户端的数据，在写回
	err := request.GetConnection().SendMsg(200, []byte("ping, there is server..."))
	if err != nil {
		fmt.Println("send msg error: ", err)
		return
	}
}

type HelloRouter struct {
	znet.BaseRouter
}

//func (pr *PingRouter) PreHandle(request ziface.IRequest) {
//	fmt.Println("call before router handle...")
//	_, err := request.GetConnection().GetTCPConnection().Write([]byte("PreHandle..."))
//	if err != nil {
//		fmt.Println("PreHandle err")
//		return
//	}
//}

// Handle 处理业务的主方法
func (hr *HelloRouter) Handle(request ziface.IRequest) {
	fmt.Println("recv client msg: id = ", request.GetMsgId(), " len = ", len(request.GetData()), " msg = ", string(request.GetData()))
	// 先读取客户端的数据，在写回
	err := request.GetConnection().SendMsg(201, []byte("hello, there is server..."))
	if err != nil {
		fmt.Println("send msg error: ", err)
		return
	}
}

func begin(conn ziface.IConnection) {
	fmt.Println("==== there is begin ====")
	if err := conn.SendMsg(202, []byte("BEGIN")); err != nil {
		fmt.Println(err)
	}

	conn.SetProperty("name", "rainbow")
	conn.SetProperty("lover", "zhanghongcai")
}

func end(conn ziface.IConnection) {
	fmt.Println("==== there is end ====")

	if name, err := conn.GetProperty("name"); err == nil {
		fmt.Println("name = ", name)
	}
	if lover, err := conn.GetProperty("lover"); err == nil {
		fmt.Println("lover = ", lover)
	}
}

func main() {
	server := znet.NewServer("zinxv0.3")

	server.SetOnConnStart(begin)
	server.SetOnConnStop(end)

	server.AddRouter(0, &PingRouter{})
	server.AddRouter(1, &HelloRouter{})
	server.Serve()
}
